<!--
* description: 整车销售---订单交付
* author:xlc
* createdDate: 2020-11-30
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      v-loading="allLoading"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :callback-obj="callbackObj"
    />
    <edit
      v-if="editPopupsVisible"
      :key="editPopupsKey"
      :popups-visible="editPopupsVisible"
      :data-for-form="editRowData"
      :popups-state="editPopupsState"
      :title-name="titleName"
      @close="close"
      @save="save"
    />
    <print-documents
      v-if="printPopupsVisible"
      :key="printPopupsKey"
      :popups-visible="printPopupsVisible"
      :data-for-form="printRowData"
      @closePrint="closePrint"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/vesalesapi.js'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import printDocuments from './printDocuments'
import Vue from 'vue'
export default {
  name: 'Orderdelivery',
  components: {
    OneTableTemplate,
    printDocuments,
    Edit
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      allLoading: false,
      printPopupsKey: 'printPopupsKey',
      editPopupsKey: 'editPopupsKey',
      titleName: '',
      editRowData: {},
      printRowData: {},
      editPopupsState: '',
      editPopupsVisible: false,
      printPopupsVisible: false,
      // 网格查询API配置对象
      apiConfig: orgApis.orderSelectOrder,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          name: 'search', // 按钮图标样式
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          name: 'reset',
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          clickEvent: () => this.confirm(),
          disabled: true,
          text: '交车确认',
          name: 'confirm',
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          type: '',
          size: 'small',
          clickEvent: () => { this.allow() },
          text: '打印交车单',
          disabled: true,
          name: 'printing',
          position: 'left'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '订单编号：',
              codeField: 'saleOrderCode',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '客户名称：',
              codeField: 'custName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '联系电话：',
              codeField: 'custTel',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: 'VIN：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '交付门店：',
              codeField: 'deliveryDlrId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              oFields: 'deliveryDlrId,deliveryDlrShortName',
              customObj: {
                api: orgApis.ListOfDeliveryStore
              }
            },
            {
              compKey: 'compKey6',
              labelName: '交付专员：',
              codeField: 'empId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              parentFileds: 'value:deliveryDlrId',
              oFields: 'empId,empName',
              customObj: {
                listQuery: { deliveryDlrId: '' },
                api: orgApis.ListOfdeliveryPersonnel
              }
            },
            {
              compKey: 'compKey7',
              labelName: '预计交付时间：',
              codeField: 'preDeliverDateStartTime,preDeliverDateEndTime',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'daterange',
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '实际交付时间：',
              codeField: 'deliveryDateStartTime,deliveryDateEndTime',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'daterange',
              isMust: false
            }
          ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            // {
            //   prop: 'controlBtn',
            //   label: '车联网激活',
            //   codeField: 'controlBtn',
            //   align: 'center',
            //   isComponent: true,
            //   comps: [
            //     {
            //       compKey: 'propKey1',
            //       labelName: '激活',
            //       align: 'center',
            //       codeField: 'editControlBtn',
            //       clickEvent: index => { this.showEdit(index) },
            //       component: () => import('@/components/org/linkButton')
            //     }
            //   ]
            // },
            {
              prop: 'orderStatus', hidden: true,
              label: '订单状态', width: 120
            },
            {
              prop: 'orderStatusName',
              label: '订单状态', width: 120
            },
            {
              prop: 'saleOrderCode',
              label: '订单编号',
              width: 120
            },
            {
              prop: 'custName',
              label: '客户名称', width: 120
            },
            {
              prop: 'custTel',
              label: '联系电话', width: 120
            },
            {
              prop: 'caEmpName',
              label: '销售人员', width: 120
            },
            {
              prop: 'dlrShortName',
              label: '交付门店', width: 120
            },
            {
              prop: 'empName',
              label: '交付专员', width: 120
            },
            {
              prop: 'vin',
              label: 'VIN码', width: 160
            },
            {
              prop: 'carSeriesCn',
              label: '车系', width: 120
            },
            {
              prop: 'carConfigCn',
              label: '基础车型名称', width: 120
            },
            {
              prop: 'optionalPagName',
              label: '选装包', width: 120
            },
            {
              prop: 'carColorName',
              label: '车身颜色', width: 120
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色', width: 120
            },
            {
              prop: 'preDeliverDate',
              label: '预计交付时间', width: 180
            },
            {
              prop: 'deliverDate',
              label: '实际交付时间', width: 180
            }
          ],
      formField: {
        saleOrderCode: '',
        custName: '',
        custTel: '',
        vin: '',
        deliveryDlrId: '',
        empId: '',
        deliveryDateStartTime: '',
        deliveryDateEndTime: '',
        preDeliverDateStartTime: '',
        preDeliverDateEndTime: ''
      },
      // 是否使用刷新Key的方式刷新弹窗
      resetDialogKey: false,
      sList: [],
      selectList: [],
      // 单表格模版页面组件回调事件
      callbackObj: {
        // // 当选择项发生变化时会触发该事件（多选时）
        // dlrCode  dlrShortName delDleCode  delDlrShortName  licenseAddr  signatoryName  custType  invoiceDate  deliverDate vin   carBrandCode  carColorCode carColorName  carIncolorCode  carIncolorName  carSeriesCode carSeriesCn  carConfigCode  carConfigCn  optionalPagCode  optionalPagName  produceDate  batteryCode  deivingMotor  genderCode  credTypeCode  signaToryIdCard  caEmpId
        onCheckSelectChange: (selection) => {
          // this.sList = selection.reduce((pre, cur) => {
          //   pre.push({
          //     dlrIDS: cur.dlrIDS,
          //     signatoryPhone: cur.signatoryPhone,
          //     saleOrderSign: cur.saleOrderSign,
          //     dlrCustNO: cur.dlrCustNO,
          //     dlrID: cur.dlrID,
          //     carId: cur.carId,
          //     dlrCode: cur.dlrCode,
          //     dlrShortName: cur.dlrShortName,
          //     delDleCode: cur.delDleCode,
          //     delDlrShortName: cur.delDlrShortName,
          //     licenseAddr: cur.licenseAddr,
          //     signatoryName: cur.signatoryName,
          //     custType: cur.custType,
          //     invoiceDate: cur.invoiceDate,
          //     deliverDate: cur.deliverDate,
          //     vin: cur.vin,
          //     carBrandCode: cur.carBrandCode,
          //     carColorCode: cur.carColorCode,
          //     carColorName: cur.carColorName,
          //     carIncolorCode: cur.carIncolorCode,
          //     carIncolorName: cur.carIncolorName,
          //     carSeriesCode: cur.carSeriesCode,
          //     carSeriesCn: cur.carSeriesCn,
          //     carConfigCode: cur.carConfigCode,
          //     carConfigCn: cur.carConfigCn,
          //     optionalPagCode: cur.optionalPagCode,
          //     optionalPagName: cur.optionalPagName,
          //     signaToryPhone: cur.signaToryPhone,
          //     produceDate: cur.produceDate,
          //     batteryCode: cur.batteryCode,
          //     deivingMotor: cur.deivingMotor,
          //     genderCode: cur.genderCode,
          //     credTypeCode: cur.credTypeCode,
          //     signaToryIdCard: cur.signaToryIdCard,
          //     caEmpId: cur.caEmpId,
          //     buyCustId: cur.buyCustId,
          //     signaToryName: cur.signaToryName,
          //     signaToryCompanyName: cur.signaToryCompanyName,
          //     signaToryConmpanyCode: cur.signaToryConmpanyCode,
          //     saleOrderDate: cur.saleOrderDate,
          //     salePlanCode: cur.salePlanCode,
          //     assignDate: cur.assignDate,
          //     saleOrderCodeC: cur.saleOrderCodeC
          //   })
          //   return pre
          // }, [])
          this.onCheckSelectChange1(selection)
          this.selectList = selection
        }
      }
    }
  },
  mounted() {
    this.queryTable(1)
  },
  methods: {
    // 设置表格选择框 是否禁用
    // getSelectable(row, index) {
    //   if (row.orderStatus !== '18') {
    //     return true
    //   }
    // },
    // 激活
    showEdit(index) {
      this.editRowData = this.$refs.multipleTable.list[index]
      this.editPopupsVisible = true
      this.editPopupsKey = this.$utils.generateId()
    },
    // 交车确认
    confirm() {
      this.allLoading = true
      var arr = this.selectList
      var isShip = arr.every((item) => {
        return item.orderStatus !== '18'
      })
      if (isShip) {
        const that = this
        const obj = {
          saleOrderId: [],
          updateControlId: [],
          moveState: [],
          saleOrderCode: [],
          buyUserId: [],
          vin: []
        }
        for (const k in this.selectList) {
          obj.saleOrderId.push(this.selectList[k].saleOrderId)
          obj.updateControlId.push(this.selectList[k].updateControlId)
          obj.moveState.push(this.selectList[k].moveState)
          obj.saleOrderCode.push(this.selectList[k].saleOrderCode)
          obj.buyUserId.push(this.selectList[k].buyUserId)
          obj.vin.push(this.selectList[k].vin)
        }
        const queryObj = {
        // api配置
          apiConfig: orgApis.updateOrderStatusConfirmation,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { ...obj, infoList: arr }
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then(response => {
          this.allLoading = false
          this.$message({
            message: response.msg,
            duration: 2000
          })
          if (response.result === '1') {
            this.$refs.multipleTable.$refs.multipleTable.clearSelection()
            this.queryTable()
          }
        })
      } else {
        this.allLoading = false
        this.$message({
          type: 'info',
          message: '订单已交付,不可再交付'
        })
      }
    },
    // 按钮是否可用
    onCheckSelectChange1(selection) {
      var btn1 = this.tableButtons[2]
      var btn2 = this.tableButtons[3]
      const isCheck = selection && selection.length > 0
      btn1.disabled = !isCheck
      btn2.disabled = !isCheck
    },

    // 关闭弹窗
    closePrint() {
      this.printPopupsVisible = false
      this.printPopupsKey = this.$utils.generateId()
    },
    // 打印交车单
    allow() {
      if (this.selectList.length > 1) {
        this.$message({
          message: '交车单只能单次打印',
          duration: 2000
        })
      } else {
        this.printRowData = this.selectList[0]
        this.printPopupsVisible = true
        this.printPopupsKey = this.$utils.generateId()
      }
    },
    // 保存
    save(res) {
      if (res.index) {
        this.$refs.multipleTable.list[res.index] = res
        this.close()
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      } else {
        this.$refs.multipleTable.list.push(res)
        this.close()
        this.$message({
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      }
    }
  }
}
</script>
